<template>
  <div class="login-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="登录" name="first">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="账号"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>

          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            style="width:100%;margin-bottom:30px;"
            @click.native.prevent="handleLogin"
          >登录</el-button>
        </el-form>
      </el-tab-pane>

      <!-- 注册表单 -->
      <el-tab-pane label="注册" name="second">
        <el-form
          ref="registerForm"
          autocomplete="off"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="registerForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
              @blur="verifyUsernames"
            />
          </el-form-item>

          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              v-model="registerForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="email">
            <span class="svg-container">
              <img src="@/assets/images/登录注册页/u44.png" alt="" style="width:16px">
            </span>
            <el-input
              :key="passwordType"
              v-model="registerForm.email"
              type="text"
              placeholder="邮箱验证"
              name="email"
              tabindex="2"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="mobile">
            <span class="svg-container">
              <img src="@/assets/images/登录注册页/u34.png" alt="">
            </span>
            <el-input
              v-model="registerForm.mobile"
              type="number"
              placeholder="手机号"
              name="mobile"
              tabindex="2"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="code" class="validate">
            <el-input
              :key="passwordType"
              v-model="registerForm.code"
              class="validate_input"
              type="number"
              placeholder="验证码"
              name="mobile"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <el-button :plain="true" @click="generateCode">发送验证码</el-button>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            style="width:100%;margin-bottom:30px;"
            @click.native.prevent="handleRegister"
          >注册</el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
// 引入actions的辅助函数
import { mapActions } from 'vuex';
import { setToken, getToken } from '@/utils/auth.js';
import { login, register } from '@/api/user.js';
// import { validUsername } from '@/utils/validate';
// import { login } from '@/api/user.js';

export default {
  name: 'Login',
  data() {
    return {
      // 登录表单相关
      loginForm: {
        username: '',
        password: '',
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '账号不能为空' },
          { min: 3, max: 8, message: '用户名长度必须在3-8位之间' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { min: 6, max: 16, message: '密码长度必须在6-16位之间' },
        ],
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      // 控制激活登录/注册的激活
      activeName: 'first',
      // 注册表单相关
      registerForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        code: '',
      },
      registerRules: {
        username: [
          { required: true, trigger: 'blur', message: '账号不能为空' },
          { min: 3, max: 8, message: '用户名长度必须在3-8位之间' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { min: 6, max: 16, message: '密码长度必须在6-16位之间' },
        ],
        email: [
          { required: true, trigger: 'blur', message: '邮箱不能为空' },
          {
            pattern: /^\w+@[a-z0-9]+\.[a-z]{2,4}$/,
            message: '邮箱格式不正确',
          },
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '手机号不能为空' },
          {
            pattern: /^1[3|5|7|8]\d{9}$/,
            message: '手机号格式不正确',
          },
        ],
        code: [
          { required: true, trigger: 'blur', message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' },
        ],
      },
      // 记录已经注册过的用户姓名
      names: [],
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  async created() {
    const res = await login();
    console.log(res);
  },
  methods: {
    ...mapActions(['user/login']),
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    async handleLogin() {
      this.$refs.loginForm.validate(async(valid) => {
        if (valid) {
          try {
            this.loading = true;
            // 调用接口
            // const { data } = await login(this.loginForm);
            await login(this.loginForm);
            // 自己设置一个token
            setToken('registed');
            const res = getToken();
            this['user/login'](res);
            // if (data.length <= 0) {
            //   return this.$message.warning('你还没有注册，请注册！');
            // }
            // 页面跳转
            this.$router.push('/');
          } catch (error) {
            console.log('凉了', error);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 注册
    handleRegister() {
      this.$refs.registerForm.validate(async(valid) => {
        if (valid) {
          try {
            await register(this.registerForm);
            this.names.push(this.registerForm.username);
            localStorage.setItem('username', JSON.stringify(this.names));
          } catch (error) {
            console.log(error);
          }
          this.$message.success('注册成功！');
          // console.log(this.names);
          this.activeName = 'first';
        }
      });
    },
    // 生成验证码
    generateCode() {
      const randomNum = Math.ceil(Math.random() * 1000000);
      let randomStr = randomNum.toString();
      if (randomStr.length === 5) {
        randomStr = '0' + randomStr;
      } else if (randomStr.length === 4) {
        randomStr = '0' + randomStr + '0';
      }
      this.registerForm.code = randomStr;
    },
    // 注册用户重复校验
    verifyUsernames() {
      // 获取本地储存的最新用户名
      const newNames = JSON.parse(localStorage.getItem('username'));
      newNames.some((item) => {
        if (item === this.registerForm.username) {
          return this.$message.warning('该用户已注册，请不要重复注册');
        }
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
// 这里修改输入框文本的颜色
$light_gray: black;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  // 控制tab栏切换的样式
  .el-tabs__nav-wrap::after {
    width: 0%;
  }

  .el-tabs__nav-wrap {
    overflow: hidden;
    margin-bottom: -1px;
    position: static; // 关闭相对定位
    .el-tabs__nav-scroll {
      overflow: hidden;
      position: absolute;
      left: 725px;
      top: 270px;
      .el-tabs__item {
        padding: 0 85px;
        font-size: 20px;
        // color: gray;
      }
    }
  }

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      -moz-appearance: textfield;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      //   &:-webkit-autofill {
      //     box-shadow: 0 0 0px 1000px $bg inset !important;
      //     -webkit-text-fill-color: $cursor !important;
      //   }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    background: white;
    border-radius: 5px;
    color: black;
  }

  // 修改错误提示信息
  .el-form-item__error {
    color: red;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: absolute;
    top: 100%;
    left: 0;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  background-image: url('~@/assets/images/登录注册页/u1.jpg');
  background-position: center;
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  // margin: 100px auto;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 340px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .validate {
    background: transparent;
    ::v-deep .el-form-item__content {
      display: flex;
      justify-content: space-between;
      .validate_input {
        background: #fff;
        width: 300px;
        margin-right: 30px;
        border-radius: 5px;
        .el-button {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
